<?php

namespace app\index\controller;

use think\Cache;

// 问答接口
class Qa extends User
{
	// 后台地址
	// https://jiankangpao.sichuancancer.org/azfzjkp/home/Qa/index.html

	// UPDATE `as_record` SET `openid` = CONCAT('2024_', `openid`)
	// UPDATE `user_info` SET `openid` = CONCAT('2024_', `openid`)
	// UPDATE `user_info` SET `nick_name` = CONCAT('2024_', `nick_name`)

	// 地图市洲列表
	// https://jiankangpao.sichuancancer.org/azfzjkp/Index/Qa/regionListForMap.html
	public function regionListForMap()
	{
		$openid = input('openid/s');
		$nick_name = input('nick_name/s');

		// 保存昵称
		if (!empty($nick_name)) {
			db("user_info")
				->where('openid', $openid)
				->update([
					'nick_name' => $nick_name,
					'update_time' => date("Y-m-d H:i:s", time())
				]);
		}

		$finishedCgtCount = 0;
		$finishedCgt = 'yes';
		$regionList = $this->regionList;
		foreach ($regionList as $key => $region) {
			$asRecordCount = db("as_record")
				->where('openid', $openid)
				->where('region', $region['name'])
				->where('classify', '闯关题')
				->count();
			$finished = $asRecordCount > 0 ? 'yes' : 'no';
			if ($finished == 'no') {
				$finishedCgt = 'no';
			} else {
				$finishedCgtCount++;
			}
			$regionList[$key]['finished'] = $finished;
		}
		$asRecordCount = db("as_record")
			->where('openid', $openid)
			->where('classify', '科普题')
			->count();
		$finishedKpt = $asRecordCount > 0 ? 'yes' : 'no';

		return json(array(
			'code' => '0', 'msg' => "取得地图市洲列表成功",
			'data' => [
				'regionList' => $regionList,
				'finishedCgtCount' => $finishedCgtCount,
				'finishedCgt' => $finishedCgt,
				'finishedKpt' => $finishedKpt,
			]
		));
	}

	// 问答答题页面：取得题目列表
	// https://jiankangpao.sichuancancer.org/azfzjkp/Index/Qa/qaList.html
	public function qaList()
	{
		$openid = input('openid/s');

		$qaList = [];
		$qaListIndex = 0;
		$regionIndex = 0;

		// 1.取得【基本情况】题
		$regionArr = [];
		$qaBankList = db("qa_bank")
			->field("id,q_no,region,classify,title,analysis,type_tag,qa_json")
			->where('classify', '基本情况')
			->where("status", 1)
			->cache(true, $this->cacheTime)
			->order('q_no asc')
			->select();
		if (!empty($qaBankList)) {
			foreach ($qaBankList as $key => $qa) {
				$qa_json = json_decode($qa['qa_json'], true);
				unset($qa['qa_json']);

				$qa['select_list'] = $qa_json;
				$qa['my_answer'] = "";
				$qa['is_right'] = "";

				$qaBankList[$key] = $qa;
			}

			$asRecordCount = db("as_record")
				->where('openid', $openid)
				->where('classify', '基本情况')
				->count();
			$finished = $asRecordCount > 0 ? 'yes' : 'no';

			$regionArr[] = ['finished' => $finished, 'region' => '基本情况', 'qa_bank' => $qaBankList];
			$qaList[] = [
				'classify' => '基本情况',
				'finished' => $finished,
				'region' => $regionArr,
				'prompt' => "在“健康跑”开始之前，需要花费您几分钟的时间填写个人基本信息，以了解居民癌症防治核心知识知晓水平的相关因素。基本信息共7题，均为选择类型，填写为匿名，所填信息都将会严格保密。感谢您的合作！"
			];
		}
		if ($finished == 'yes') {
			// 基本情况全部做完
			$qaListIndex = 1; //直接从闯关题开始做
			$regionIndex = 0;
		}

		// 2.取得【闯关题】题
		$regionArr = [];
		foreach ($this->regionList as $key => $region) {
			$region = $region['name'];
			$qaBankList = db("qa_bank")
				->field("id,q_no,region,classify,title,analysis,type_tag,qa_json")
				->where('classify', '闯关题')
				->where('region', $region)
				->where("status", 1)
				->cache(true, $this->cacheTime)
				->order('q_no asc')
				->select();
			if (!empty($qaBankList)) {
				// 判断是否已经答过题了
				$asRecordCount = db("as_record")
					->where('openid', $openid)
					->where('region', $region)
					->where('classify', '闯关题')
					->count();
				$finished = $asRecordCount > 0 ? 'yes' : 'no';
				if ($finished == 'yes') {
					//从下一个市洲开始
					$regionIndex++;
				}

				foreach ($qaBankList as $key => $qa) {
					$is_right = '';
					$select_list = json_decode($qa['qa_json'], true);
					unset($qa['qa_json']);

					// 答题记录
					$asRecord = db("as_record")
						->field("my_answer_idxs")
						->where('openid', $openid)
						->where('qa_back_id', $qa['id'])
						->find();
					if (!empty($asRecord)) {
						$rightAnswer = [];
						$is_right = 'yes';
						$myAnswerIdxs = json_decode($asRecord['my_answer_idxs']);
						foreach ($select_list as $answer_idx => $select) {
							// 记录正确答案
							if ($select['score'] > 0) {
								$rightAnswer[] = $this->letters[$answer_idx];
							}
							if (in_array($answer_idx, $myAnswerIdxs)) {
								// 设置原来的选择的选项
								$select_list[$answer_idx]["is_selected"] = "yes";
								if ($select['score']  == '0') {
									// 选择了错误的答案
									$is_right = 'no';
								}
							} else if ($select['score'] > 0) {
								// 正确的答案没有选
								$is_right = 'no';
							}
						}
						$qa['right_answer'] = implode('、', $rightAnswer);
					}

					$qa['select_list'] = $select_list;
					$qa['my_answer'] = "";
					$qa['is_right'] = $is_right;
					$qaBankList[$key] = $qa;
				}
				$regionArr[] = ['finished' => $finished, 'region' => $region, 'qa_bank' => $qaBankList];
			}
		}
		$qaList[] = [
			'classify' => '闯关题',
			'finished' => $finished,
			'region' => $regionArr,
			'prompt' => "癌防知识健康跑即将开始！每个市州2-3个闯关题，想知道自己癌防知识的整体知晓水平，那得坚持跑完21个市州哟，加油！"
		];
		if ($finished == 'yes') {
			// 闯关题全部做完
			$qaListIndex = 2; //直接从科普题开始做
			$regionIndex = 0;
		}

		// 3.取得【科普题】题
		$regionArr = [];
		$qaBankList = db("qa_bank")
			->field("id,q_no,region,classify,title,analysis,type_tag,qa_json")
			->where('classify', '科普题')
			->where("status", 1)
			->cache(true, $this->cacheTime)
			->order('q_no asc')
			->select();
		if (!empty($qaBankList)) {
			foreach ($qaBankList as $key => $qa) {
				$qa_json = json_decode($qa['qa_json'], true);
				unset($qa['qa_json']);

				$qa['select_list'] = $qa_json;
				$qa['my_answer'] = "";
				$qa['is_right'] = "";

				$qaBankList[$key] = $qa;
			}
			$asRecordCount = db("as_record")
				->where('openid', $openid)
				->where('classify', '科普题')
				->count();
			$finished = $asRecordCount > 0 ? 'yes' : 'no';
			$regionArr[] = ['finished' => $finished, 'region' => '科普题', 'qa_bank' => $qaBankList];
			$qaList[] = [
				'classify' => '科普题',
				'finished' => $finished,
				'region' => $regionArr,
				'prompt' => ""
			];
		}

		return json(array(
			'code' => '0',
			'msg' => "题目列表取得成功",
			'data' => ['qaList' => $qaList, 'qaListIndex' => $qaListIndex, 'regionIndex' => $regionIndex]
		));
	}

	// 提交我的回答
	// https://jiankangpao.sichuancancer.org/azfzjkp_dev/Index/Qa/myAs.html?qa_main_id=1
	public function myAs()
	{
		$openid = input('openid/s');
		$region = input('region/a');

		$record = [];
		$record['openid'] = $openid;
		foreach ($region['qa_bank'] as $key => $qa_bank) {
			$record['qa_back_id'] = $qa_bank['id'];
			$record['q_no'] = $qa_bank['q_no'];
			$record['classify'] = $qa_bank['classify'];
			$record['region'] = $qa_bank['region'];
			$record['title'] = $qa_bank['title'];

			if ($qa_bank['classify'] == '基本情况' && $qa_bank['q_no'] == '07') {
				// 基本情况-常住地
				$record['is_right'] = '';
				$my_answer = '';
				$my_answer = $qa_bank['my_answer'][0];
				$my_answer .= $qa_bank['my_answer'][0] == $qa_bank['my_answer'][1] ? '' : $qa_bank['my_answer'][1];
				$my_answer .= $qa_bank['my_answer'][1] == $qa_bank['my_answer'][2] ? '' : $qa_bank['my_answer'][2];
				$record['my_answer'] = $my_answer;
			} else {
				$my_answer_idxs = [];
				$my_answer = [];
				$is_right = 'yes';
				foreach ($qa_bank['select_list'] as $key => $select) {
					if ($select["is_selected"] == 'yes') {
						$my_answer_idxs[] = $key;
						// 记录选择的选项
						if ($qa_bank['classify'] == '基本情况') {
							$my_answer[] = $select['text']; // . '\r\n';
						} else {
							$my_answer[] = $this->letters[$key] . '：' . $select['text']; // . '\r\n';
						}

						// 判断是否选择了错误的答案
						if ($select['score'] == '0' && $qa_bank['classify'] == '闯关题') {
							// 选择了错误的答案
							$is_right = 'no';
						}
					} else if ($select['score'] > 0 && $qa_bank['classify'] == '闯关题') {
						// 正确的答案没有选
						$is_right = 'no';
					}
				}

				$record['my_answer_idxs'] = json_encode($my_answer_idxs);
				$record['my_answer'] = implode("\r\n", $my_answer);
				if ($qa_bank['classify'] == '闯关题') {
					// 闯关题 才判断对错
					$record['is_right'] = $is_right;
				}
			}

			$asRecord = db("as_record")
				->where('openid', $openid)
				->where('qa_back_id', $qa_bank['id'])
				->find();
			if (empty($asRecord)) {
				db("as_record")->insert($record);
			} else {
				db("as_record")
					->where('id', $asRecord['id'])
					->update($record);
			}
		}

		return json(array('code' => '0', 'msg' => "提交我的回答", 'data' => []));
	}

	// 提交我的回答
	// https://jiankangpao.sichuancancer.org/azfzjkp_dev/Index/Qa/myQaResult.html?qa_main_id=1
	public function myQaResult()
	{
		$openid = input('openid/s');

		$rightCount = db("as_record")
			->where('openid', $openid)
			->where('classify', '闯关题')
			->where('is_right', 'yes')
			->count();

		$allCount = db("qa_bank")
			// ->where('openid', $openid)
			->where('classify', '闯关题')
			->count();

		$myScore = sprintf("%.2f", ($rightCount / $allCount)) * 100;
		// （最终授牌类别）    
		// 恭喜你，已完成所有知识闯关，特授予您XX称号，快到朋友圈炫耀一下吧
		if ($myScore >= 90) {
			// 正确率90%及以上——癌防知识知晓“六边形战士”
			$msg = "癌防知识知晓“六边形战士”";
		} else if ($myScore >= 80) {
			// 正确率80%及以上，但不足90%——癌防知识知晓“牛人”
			$msg = "癌防知识知晓“牛人”";
		} else if ($myScore >= 80) {
			// 正确率70%及以上，但不足80%——癌防知识知晓“达人”
			$msg = "癌防知识知晓“达人”";
		} else {
			// 正确率70%以下——癌防知识知晓“卫士”
			$msg = "癌防知识知晓“卫士”";
		}
		$user_info = db("user_info")->where('openid', $openid)->find();

		if (!empty($user_info) && !empty($user_info['nick_name'])) {
			// 过滤特殊字符
			// $nickName = iconv('UTF-8', 'GBK//IGNORE', $user_info['nick_name']);
			// $nickName = iconv('GBK', 'UTF-8//IGNORE', $nickName);
			// $nickName = mb_substr($nickName, 0, 6);
			$nickName = mb_substr($user_info['nick_name'], 0, 6);
		} else {
			$nickName = "微信用户";
		}

		return json(array('code' => '0', 'msg' => "提交我的回答", 'data' => [
			"nick_name" =>  $nickName,
			'allCount' => $allCount,
			'rightCount' => $rightCount,
			'myScore' => $myScore . "分",
			// 'msg' => "恭喜您获得{$msg}称号",
			'msg' => "$msg",
		]));
	}
}
